import { useState, useCallback } from 'react';
import { GameState, GameSettings, PlayerStats, GameProgress, WarehouseState, InventoryItem, EquipmentType, ActionType, Position, Enemy, SessionResult } from '../types/game';
import { 
  saveGame, 
  loadGame, 
  loadWarehouse, 
  addItemToWarehouse,
  removeItemFromWarehouse,
  sellItemFromWarehouse,
  hasSaveData 
} from '../utils/localStorage';
import { EquipmentManager } from '../utils/equipmentManager';
import { SessionManager } from '../utils/sessionManager';

// 初始装备槽位
const createInitialEquipment = () => ({
  head: null,
  body: null,
  primaryWeapon: null,
  secondaryWeapon: null,
  knife: null,
  backpack: null,
  ammoPouch: null,
});

// 初始计算属性
const createInitialCalculatedStats = () => ({
  totalAttack: 0,
  totalDefense: 0,
  totalAccuracy: 0,
  totalSpeed: 0,
  inventoryCapacity: 10, // 基础容量
  ammoCapacity: 0,
});

// 初始游戏状态
const createInitialGameState = (): GameState => ({
  currentScene: 'start',
  playerStats: {
    name: '冒险者',
    level: 1,
    health: 100,
    maxHealth: 100,
    energy: 100,
    maxEnergy: 100,
    experience: 0,
    coins: 100, // 给新玩家一些初始搜币
    equipment: createInitialEquipment(),
    calculatedStats: createInitialCalculatedStats(),
  },
  inventory: [],
  gameProgress: {
    currentChapter: 1,
    completedQuests: [],
    flags: {},
    visitedScenes: [],
  },
  settings: {
    textSpeed: 1,
    autoSave: true,
    soundEnabled: true,
    language: 'zh-CN',
  },
});

export const useGameState = () => {
  const [gameState, setGameState] = useState<GameState>(createInitialGameState());
  const [warehouse, setWarehouse] = useState<WarehouseState>(loadWarehouse());
  const [currentScreen, setCurrentScreen] = useState<'start' | 'game' | 'settings' | 'startSession' | 'session'>('start');
  const [warehouseOpen, setWarehouseOpen] = useState(false);
  const [equipmentOpen, setEquipmentOpen] = useState(false);



  // 新游戏
  const startNewGame = useCallback(() => {
    const newGameState = createInitialGameState();
    setGameState(newGameState);
    setCurrentScreen('startSession')
    
    // 自动保存
    if (newGameState.settings.autoSave) {
      saveGame(newGameState, warehouse);
    }
  }, [warehouse]);

  // 保存游戏数据
  const saveGameData = useCallback(() => {
    return saveGame(gameState, warehouse);
  }, [gameState, warehouse]);

  // 加载游戏数据
  const loadGameData = useCallback(() => {
    const saveData = loadGame();
    if (saveData) {
      setGameState(saveData.gameState);
      setWarehouse(saveData.warehouse);
      setCurrentScreen('startSession')
      return true;
    }
    return false;
  }, []);

  // 检查是否有存档
  const checkHasSaveData = useCallback(() => {
    return hasSaveData();
  }, []);

  // 清除所有存档数据
  const clearAllSaveData = useCallback(() => {
    // 清除游戏存档
    localStorage.removeItem('gameState');
    // 清除仓库存档
    localStorage.removeItem('warehouse');
    // 重置到初始状态
    setGameState(createInitialGameState());
    setWarehouse({
      items: [],
      capacity: 100,
      upgrades: [],
      coins: 0
    });
    setCurrentScreen('start');
    setWarehouseOpen(false);
    setEquipmentOpen(false);
  }, []);

  // 更新游戏状态
  const updateGameState = useCallback((updates: Partial<GameState>) => {
    setGameState(prev => {
      // 深度合并，特别处理 playerStats
      const newState = {
        ...prev,
        ...updates,
        playerStats: updates.playerStats ? {
          ...prev.playerStats,
          ...updates.playerStats,
          // 如果有 equipment 更新，确保它不会被覆盖
          equipment: updates.playerStats.equipment ? {
            ...prev.playerStats.equipment,
            ...updates.playerStats.equipment
          } : prev.playerStats.equipment
        } : prev.playerStats
      };
      

      
      // 自动保存
      if (newState.settings.autoSave) {
        saveGame(newState, warehouse);
      }
      
      return newState;
    });
  }, [warehouse]);

  // 更新玩家状态
  const updatePlayerStats = useCallback((updates: Partial<PlayerStats>) => {
    console.log('updatePlayerStats called with:', updates);
    console.log('Current playerStats before update:', gameState.playerStats);
    
    const newPlayerStats = { ...gameState.playerStats, ...updates };
    console.log('New playerStats after merge:', newPlayerStats);
    
    updateGameState({
      playerStats: newPlayerStats
    });
  }, [gameState.playerStats, updateGameState]);

  // 更新游戏进度
  const updateGameProgress = useCallback((updates: Partial<GameProgress>) => {
    updateGameState({
      gameProgress: { ...gameState.gameProgress, ...updates }
    });
  }, [gameState.gameProgress, updateGameState]);

  // 更新设置
  const updateSettings = useCallback((updates: Partial<GameSettings>) => {
    updateGameState({
      settings: { ...gameState.settings, ...updates }
    });
  }, [gameState.settings, updateGameState]);

  // 切换场景
  const changeScene = useCallback((sceneId: string) => {
    const visitedScenes = [...gameState.gameProgress.visitedScenes];
    if (!visitedScenes.includes(sceneId)) {
      visitedScenes.push(sceneId);
    }

    updateGameState({
      currentScene: sceneId,
      gameProgress: {
        ...gameState.gameProgress,
        visitedScenes,
      },
    });
  }, [gameState.gameProgress, updateGameState]);

  // 仓库相关方法
  const addToWarehouse = useCallback((item: InventoryItem) => {
    if (addItemToWarehouse(item)) {
      setWarehouse(loadWarehouse());
      return true;
    }
    return false;
  }, []);

  const removeFromWarehouse = useCallback((itemId: string, quantity: number = 1) => {
    if (removeItemFromWarehouse(itemId, quantity)) {
      setWarehouse(loadWarehouse());
      return true;
    }
    return false;
  }, []);

  // 出售仓库中的物品
  const sellFromWarehouse = useCallback((itemId: string, quantity: number = 1) => {
    const earnedCoins = sellItemFromWarehouse(itemId, quantity);
    if (earnedCoins > 0) {
      setWarehouse(loadWarehouse());
      return earnedCoins;
    }
    return 0;
  }, []);



  // 游戏结束时将物品保存到仓库
  const endGameAndSaveToWarehouse = useCallback(() => {
    gameState.inventory.forEach(item => {
      addToWarehouse(item);
    });
    
    // 清空当前游戏背包
    updateGameState({
      inventory: []
    });
    
    setCurrentScreen('start');
  }, [gameState.inventory, addToWarehouse, updateGameState]);

  // 装备管理功能
  const equipItem = useCallback((item: InventoryItem, slotType: EquipmentType) => {
    const result = EquipmentManager.equipItem(gameState.playerStats.equipment, item, slotType);
    
    if (result.success) {
      // 计算新的属性
      const newCalculatedStats = EquipmentManager.calculateStats(result.newEquipment);
      
      // 使用函数式更新确保我们基于最新状态
      setGameState(currentState => {
        // 创建完全新的状态对象
        const updatedState = {
          ...currentState,
          playerStats: {
            ...currentState.playerStats,
            equipment: { ...result.newEquipment },
            calculatedStats: newCalculatedStats
          }
        };
        
        return updatedState;
      });
      
      // 处理仓库操作
      setTimeout(() => {
        // 如果有装备被替换下来，添加回仓库
        if (result.unequippedItem) {
          addToWarehouse(result.unequippedItem);
        }

        // 从仓库中移除新装备的物品
        removeFromWarehouse(item.id, 1);
      }, 100);
      
      // 暂时禁用自动保存来测试
      // setTimeout(() => {
      //   if (gameState.settings.autoSave) {
      //     const currentState = { ...gameState, playerStats: { ...gameState.playerStats, equipment: result.newEquipment, calculatedStats: newCalculatedStats } };
      //     saveGame(currentState, warehouse);
      //   }
      // }, 200);

      return true;
    }
    
    return false;
  }, [gameState.playerStats.equipment]);

  const unequipItem = useCallback((slotType: EquipmentType) => {
    const result = EquipmentManager.unequipItem(gameState.playerStats.equipment, slotType);
    
    if (result.unequippedItem) {
      // 更新装备槽位
      const newCalculatedStats = EquipmentManager.calculateStats(result.newEquipment);
      
      updatePlayerStats({
        equipment: result.newEquipment,
        calculatedStats: newCalculatedStats
      });

      // 将卸下的装备添加回仓库
      addToWarehouse(result.unequippedItem);

      return true;
    }
    
    return false;
  }, [gameState.playerStats.equipment, updatePlayerStats, addToWarehouse]);

  // 仓库抽屉操作
  const openWarehouse = useCallback(() => {
    setWarehouseOpen(true);
  }, []);

  const closeWarehouse = useCallback(() => {
    setWarehouseOpen(false);
  }, []);

  // 装备抽屉操作
  const openEquipment = useCallback(() => {
    setEquipmentOpen(true);
  }, []);

  const closeEquipment = useCallback(() => {
    setEquipmentOpen(false);
  }, []);

  return {
    gameState,
    warehouse,
    currentScreen,
    setCurrentScreen,
    warehouseOpen,
    equipmentOpen,
    startNewGame,
    saveGameData,
    loadGameData,
    checkHasSaveData,
    clearAllSaveData,
    updateGameState,
    updatePlayerStats,
    updateGameProgress,
    updateSettings,
    changeScene,
    addToWarehouse,
    removeFromWarehouse,
    sellFromWarehouse,
    endGameAndSaveToWarehouse,
    openWarehouse,
    closeWarehouse,
    openEquipment,
    closeEquipment,
    // 装备管理
    equipItem,
    unequipItem,
    // 对局管理
    startSession: useCallback((selectedItems: InventoryItem[]) => {
      const session = SessionManager.createSession(selectedItems);
      updateGameState({
        currentSession: session,
        currentScene: 'session'
      });
      // 切换到对局界面
      setCurrentScreen('session');
    }, [updateGameState]),
    
    executeSessionAction: useCallback((actionType: ActionType, targetPosition?: Position, targetEnemy?: Enemy, containerId?: string) => {
      if (!gameState.currentSession) return;
      
      // 如果是容器搜索，使用专门的方法
      if (actionType === ActionType.SEARCH_CONTAINER && containerId) {
        const result = SessionManager.executeContainerSearch(gameState.currentSession, containerId);
        
        updateGameState({
          currentSession: result.session
        });
        
        // 处理对局结束
        if (result.result !== 'continue') {
          const sessionResult = result.result === 'extracted' ? SessionResult.SUCCESS : 
                              result.result === 'killed' ? SessionResult.KILLED : 
                              SessionResult.TIMEOUT;
          
          const rewards = SessionManager.calculateRewards(result.session, sessionResult);
          
          // 更新仓库和背包
          if (sessionResult === SessionResult.SUCCESS) {
            // 成功：保留所有物品，添加到仓库
            rewards.keptItems.forEach(item => addToWarehouse(item));
            // 更新搜币
            updatePlayerStats({
              coins: gameState.playerStats.coins + rewards.coinReward
            });
          }
          
          // 结束对局并返回主菜单
          updateGameState({
            currentSession: undefined,
            currentScene: 'start'
          });
          setCurrentScreen('start');
        }
        
        return {
          message: result.message,
          sessionResult: result.result !== 'continue' ? (
            result.result === 'extracted' ? SessionResult.SUCCESS : 
            result.result === 'killed' ? SessionResult.KILLED : 
            SessionResult.TIMEOUT
          ) : undefined
        };
      }
      
      // 普通行动
      const result = SessionManager.executeAction(
        gameState.currentSession, 
        actionType, 
        targetPosition, 
        undefined, 
        targetEnemy
      );
      
      updateGameState({
        currentSession: result.session
      });
      
      // 处理对局结束
      if (result.result !== 'continue') {
        const sessionResult = result.result === 'extracted' ? SessionResult.SUCCESS : 
                            result.result === 'killed' ? SessionResult.KILLED : 
                            SessionResult.TIMEOUT;
        
        const rewards = SessionManager.calculateRewards(result.session, sessionResult);
        
        // 更新仓库和背包
        if (sessionResult === SessionResult.SUCCESS) {
          // 成功：保留所有物品，添加到仓库
          rewards.keptItems.forEach(item => addToWarehouse(item));
          // 更新搜币
          updatePlayerStats({
            coins: gameState.playerStats.coins + rewards.coinReward
          });
        }
        
        // 清除当前对局
        updateGameState({
          currentSession: undefined,
          currentScene: 'start'
        });
        setCurrentScreen('start');
        
        return {
          message: result.message,
          sessionResult,
          rewards
        };
      }
      
      return {
        message: result.message,
        foundItems: result.foundItems
      };
    }, [gameState, updateGameState, updatePlayerStats, addToWarehouse]),
    
    exitSession: useCallback(() => {
      if (gameState.currentSession) {
        // 放弃对局，失去所有物品
        updateGameState({
          currentSession: undefined,
          currentScene: 'start'
        });
        setCurrentScreen('start');
      }
    }, [gameState, updateGameState])
  };
};
